<template>
  <LayHeader :class="getHeaderClass" class="header-div__header-container">
    <div class="projectTitle"></div>
    <div class="header-div__search-container">
      <a-select
        class="header-a-select__type-select"
        v-model:value="searchType"
        placeholder="评分模型"
        @change="changeType"
      >
        <a-select-option :value="0">查企业</a-select-option>
        <a-select-option :value="1">查商品</a-select-option>
      </a-select>
      <a-select
        class="hearder-select header-a-select__type-select-result"
        v-model:value="companyName"
        show-search
        :placeholder="searchPlaceholder"
        style="width: 400px"
        :default-active-first-option="false"
        :show-arrow="false"
        :filter-option="false"
        :not-found-content="null"
        @search="getSearchList"
        allowClear
        @change="onSelect"
      >
        <a-select-option :value="item.value" v-for="(item, index) in companyList" :key="index">
          <label v-html="item.label"></label>
        </a-select-option>
      </a-select>
      <div class="header-div__search-icon" @click="searchMyWord">
        <img :src="searchImage" class="header-img__search-icon" />
      </div>
    </div>
    <div :class="`${prefixCls}-action`">
      <Notify v-if="getShowNotice" :class="`${prefixCls}-action__item notify-item`" />
      <UserDropDown :theme="getHeaderTheme" />
    </div>
    <SupplierDetails v-if="isShowDetails" :company-id="companyIdByDetails" @go-back="goBack" />
  </LayHeader>
</template>
<script lang="ts">
  import { defineComponent, unref, computed, ref } from 'vue';
  import { SearchOutlined } from '@ant-design/icons-vue';
  import { propTypes } from '/@/utils/propTypes';
  import { useRouter } from 'vue-router';
  import { debounce } from 'lodash-es';
  import searchImage from '/@/assets/images/top_search.png';

  import {Layout, message} from 'ant-design-vue';
  import { AppLogo } from '/@/components/Application';
  import LayoutMenu from '../menu/index.vue';
  import LayoutTrigger from '../trigger/index.vue';

  import { AppSearch } from '/@/components/Application';

  import { useHeaderSetting } from '/@/hooks/setting/useHeaderSetting';
  import { useMenuSetting } from '/@/hooks/setting/useMenuSetting';
  import { useRootSetting } from '/@/hooks/setting/useRootSetting';

  import { MenuModeEnum, MenuSplitTyeEnum } from '/@/enums/menuEnum';
  import { SettingButtonPositionEnum } from '/@/enums/appEnum';
  import { AppLocalePicker, UserPostChange } from '/@/components/Application';

  import { UserDropDown, LayoutBreadcrumb, FullScreen, Notify, ErrorAction } from './components';
  import { useAppInject } from '/@/hooks/web/useAppInject';
  import { useDesign } from '/@/hooks/web/useDesign';

  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { useLocale } from '/@/locales/useLocale';

  import { getGoodsAvgPriceList } from '/@/api/sourcingBigData';
  import { searchCompany } from '/@/api/supplierManage';

  export default defineComponent({
    name: 'LayoutHeader',
    components: {
      LayHeader: Layout.Header,
      AppLogo,
      LayoutTrigger,
      LayoutBreadcrumb,
      LayoutMenu,
      UserDropDown,
      AppLocalePicker,
      FullScreen,
      Notify,
      AppSearch,
      ErrorAction,
      SettingDrawer: createAsyncComponent(() => import('/@/layouts/default/setting/index.vue'), {
        loading: true,
      }),
      UserPostChange,
    },
    props: {
      fixed: propTypes.bool,
    },
    setup(props) {
      const router = useRouter();
      const { prefixCls } = useDesign('layout-header');
      const {
        getShowTopMenu,
        getShowHeaderTrigger,
        getSplit,
        getIsMixMode,
        getMenuWidth,
        getIsMixSidebar,
        getCollapsed,
      } = useMenuSetting();
      const { getUseErrorHandle, getShowSettingButton, getSettingButtonPosition } =
        useRootSetting();

      const {
        getHeaderTheme,
        getShowFullScreen,
        getShowNotice,
        getShowContent,
        getShowBread,
        getShowHeaderLogo,
        getShowHeader,
        getShowSearch,
      } = useHeaderSetting();

      const { getShowLocalePicker } = useLocale();

      const { getIsMobile } = useAppInject();

      const searchPlaceholder = computed(() =>
        searchType.value === 0
          ? '请输入企业名称，关键字越多越精准'
          : '请输入商品名称，关键字越多越精准',
      );

      const getHeaderClass = computed(() => {
        const theme = unref(getHeaderTheme);
        return [
          prefixCls,
          {
            [`${prefixCls}--fixed`]: props.fixed,
            [`${prefixCls}--mobile`]: unref(getIsMobile),
            [`${prefixCls}--${theme}`]: theme,
          },
        ];
      });

      const getShowSetting = computed(() => {
        if (!unref(getShowSettingButton)) {
          return false;
        }
        const settingButtonPosition = unref(getSettingButtonPosition);

        if (settingButtonPosition === SettingButtonPositionEnum.AUTO) {
          return unref(getShowHeader);
        }
        return settingButtonPosition === SettingButtonPositionEnum.HEADER;
      });

      const getLogoWidth = computed(() => {
        if (!unref(getIsMixMode) || unref(getIsMobile)) {
          return {};
        }
        const width = unref(getMenuWidth) < 180 ? 180 : unref(getMenuWidth);
        return { width: `${width}px` };
      });

      const getSplitType = computed(() => {
        return unref(getSplit) ? MenuSplitTyeEnum.TOP : MenuSplitTyeEnum.NONE;
      });

      const getMenuMode = computed(() => {
        return unref(getSplit) ? MenuModeEnum.HORIZONTAL : null;
      });
      let searchType = ref(0);
      let companyName: any = ref(null);
      let companyList = ref([]);
      let timer: any = null;
      let companyId = '';
      let goodsName = '';

      const getSearchList = debounce(async (val: string) => {
        if (!val || timer) {
          return;
        }
        if (!val.trim()) {
          return
        }
        if (searchType.value === 0) {
          const res = await searchCompany({
            limit: 1,
            size: 20,
            name: val.trim(),
          });
          companyList.value = res
            ? res.list.map((item) => {
                item.label = item.companyName;
                item.value = item.id;
                return item;
              })
            : [];
          // companyList.value.unshift({
          //   label: val,
          //   value: val,
          // });
        } else if (searchType.value === 1) {
          const res = await getGoodsAvgPriceList({
            keyword: val.trim(),
            pageNum: 1,
            pageSize: 20,
          });
          companyList.value = res
            ? Array.from(new Set(res.list.map((item) => item.goodsName))).map((item) => ({
                label: item,
                value: item,
              }))
            : [];
          companyList.value.unshift({
            label: val,
            value: val,
          });
        }
        timer = setTimeout(() => {
          clearTimeout(timer);
          timer = null;
        }, 200);
      }, 300);

      let myWord = '';
      function onSelect(value: string, item: any) {
        myWord = value;
        if (searchType.value === 0) {
          companyId = item.value;
        } else if (searchType.value === 1) {
          goodsName = item.value;
        }
        searchData();
      }
      const changeType = () => {
        if (Array.isArray(companyList.value) && companyList.value.length > 0) {
          companyList.value = [];
          companyName.value = undefined;
        }
      };
      const searchData = () => {
        if (searchType.value === 0) {
          // 查企业
          router.push({
            path: '/supplierSourcingMain/nbgyscx',
            query: { companyId: companyId },
          });
          // openDetails(companyId)
        } else if (searchType.value === 1) {
          router.push({
            path: '/sourcingBigData/priceSourcing',
            query: { keyword: goodsName },
          });
        }
      };
      const searchMyWord = () => {
        if (searchType.value === 1 && myWord) {
          companyName.value = myWord;
          goodsName = companyList.value[0].value;
          searchData();
        }
      };
      let isShowDetails = ref(false);
      let companyIdByDetails = ref('');
      function openDetails(id: string) {
        if (id === '-') {
          return message.warning('未查到该公司详情');
        }
        companyIdByDetails.value = id;
        isShowDetails.value = true;
      }
      function goBack() {
        isShowDetails.value = false;
      }
      return {
        prefixCls,
        getHeaderClass,
        getShowHeaderLogo,
        getHeaderTheme,
        getShowHeaderTrigger,
        getIsMobile,
        getShowBread,
        getShowContent,
        getSplitType,
        getSplit,
        getMenuMode,
        getShowTopMenu,
        getShowLocalePicker,
        getShowFullScreen,
        getShowNotice,
        getUseErrorHandle,
        getLogoWidth,
        getIsMixSidebar,
        getShowSettingButton,
        getShowSetting,
        getShowSearch,
        getCollapsed,
        searchType,
        companyName,
        companyList,
        changeType,
        searchData,
        getSearchList,
        onSelect,
        searchPlaceholder,
        searchImage,
        searchMyWord,
        isShowDetails,
        companyIdByDetails,
        openDetails,
        goBack
      };
    },
  });
</script>
<style scoped lang="less">
  .header-div__header-container {
    background: linear-gradient(180deg, #344157 0%, #505f79 100%) !important;
  }

  .header-div__search-container {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    box-sizing: border-box;
    padding-right: 30px;
    position: relative;

    .header-div__search-icon {
      width: 30px;
      height: 32px;
      background: #f5f7fa;
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      top: 0px;
      right: 30px;
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
      border-left: 1px solid #dcdfe6;

      .header-img__search-icon {
        width: 14px;
        height: 14px;
      }
    }
  }

  :deep(.header-a-select__type-select) {
    .ant-select-selector {
      border-right: none;
      border-top-right-radius: 0px !important;
      border-bottom-right-radius: 0px !important;
      border-color: #d9d9d9 !important;
      box-shadow: none !important;
    }
  }

  :deep(.header-a-select__type-select-result) {
    .ant-select-selector {
      border-top-left-radius: 0px !important;
      border-bottom-left-radius: 0px !important;
      border-color: #d9d9d9 !important;
      box-shadow: none !important;
    }
  }
</style>
<style lang="less">
  @import url('./index.less');
  .projectTitle {
    padding-left: 20px;
    font-size: 18px;
    font-weight: 600;
    line-height: 26px;
    letter-spacing: 0px;
    color: #ffffff;
  }
  :deep(.hearder-select) {
    .ant-select:not(.ant-select-customize-input) .ant-select-selector {
      background: #f5f7fa;
    }
  }
  .ant-input-affix-wrapper {
    height: 32px !important;
  }
  .ant-select-clear{
    right: 40px !important;
  }
</style>
